// subcommodityCollection.js
import { CsDouble } from '../common/csDouble.js';
import { CsFundDouble } from '../common/csFundDouble.js';
import { Engine } from '../engine.js';
import { CommodityBatchWithTax } from '../sales/sales.js';
import { SubCommodity } from './subCommodity.js';
import { CommodityCollectionCode } from './commodityCollection.js';

/**
 * 商品价格模式枚举
 */
export const SubCommodityCollectionPriceMode = {
    retailPrice: 0,    // 零售价
    wholesalePrice: 1, // 批发价
    purchasePrice: 2   // 采购价
};

/**
 * 子商品集合类
 * 管理同一子商品的多个批次（用于阶梯价）
 */
export class SubCommodityCollection {
    /**
     * @param {Object} params
     * @param {SubCommodity} params.subCommodity 子商品
     * @param {Array<CommodityBatchWithTax>} [params.subCommodityBatches] 初始批次列表
     */
    constructor({ subCommodity, subCommodityBatches = [] }) {
        /** @type {SubCommodity} 规格商品信息 */
        this.subCommodity = subCommodity;

        /** @type {Array<CommodityBatchWithTax>} 规格商品集合 */
        this._subCommodityBatchList = [...subCommodityBatches];
    }

    /**
     * 创建带有初始批次的子商品集合
     * @param {Object} params
     * @param {SubCommodity} params.subCommodity 子商品
     * @param {boolean} params.initSubCommodityBatch 是否初始化批次
     * @param {SubCommodityCollectionPriceMode} params.priceMode 价格模式
     * @param {CsDouble} params.inventoryCount 库存数量
     * @returns {SubCommodityCollection}
     */
    static createWithSubCommodity({
        subCommodity,
        initSubCommodityBatch = true,
        priceMode,
        inventoryCount,
        /// 是否强制不带税 用于库存操作时不计税价
        withoutTaxForce = false,
    }) {
        console.log('createWithSubCommodity', subCommodity);
        const collection = new SubCommodityCollection({ subCommodity });

        if (initSubCommodityBatch) {
            let price;
            switch (priceMode) {
                case SubCommodityCollectionPriceMode.retailPrice:
                    price = subCommodity.retailPrice;
                    break;
                case SubCommodityCollectionPriceMode.wholesalePrice:
                    price = subCommodity.wholesalePrice;
                    break;
                case SubCommodityCollectionPriceMode.purchasePrice:
                    price = subCommodity.purchasePrice;
                    break;
                default:
                    price = CsFundDouble.zero();
            }



            let taxRate = 0;  // 不计税价格

            if (!withoutTaxForce) {
                if ((priceMode === SubCommodityCollectionPriceMode.retailPrice ||
                    priceMode === SubCommodityCollectionPriceMode.wholesalePrice) &&
                    Engine.getOrgSettings().enableSalesWithTaxDetail) {
                    taxRate = -1; // 系统配置税率

                } else if (priceMode === SubCommodityCollectionPriceMode.purchasePrice &&
                    Engine.getOrgSettings().enablePurchaseWithTaxDetail) {
                    taxRate = -1; // 系统配置税率

                } else {
                    taxRate = 0;  // 不计税价格
                }
            }

            const batch = new CommodityBatchWithTax({
                commodity: subCommodity,
                count: null, // 初始数量为空
                batchPrice: CsFundDouble.zero(),
                singlePrice: price,
                inventoryCount: inventoryCount.value,
                taxRate: taxRate,
            });

            collection._subCommodityBatchList.push(batch);
        }

        return collection;
    }

    /**
     * 获取商品批次列表（只读）
     * @returns {Array<CommodityBatchWithTax>}
     */
    get subCommmodityBatchList() {
        return Object.freeze([...this._subCommodityBatchList]);
    }

    /**
     * 添加含税商品批次
     * @param {CommodityBatchWithTax} batch 
     * @returns {CommodityCollectionCode}
     */
    addSubCommodityBatchWithTax(batch) {
        if (batch.commodity.id !== this.subCommodity.id) {
            return CommodityCollectionCode.SubCommodityBatchNotBelongToSubCommodity;
        }

        this._subCommodityBatchList.push(batch);
        return CommodityCollectionCode.Succeed;
    }

    /**
     * 添加普通商品批次
     * @param {CommodityBatch} batch 
     * @returns {CommodityCollectionCode}
     */
    addSubCommodityBatch(batch) {
        if (batch.commodity.id !== this.subCommodity.id) {
            return CommodityCollectionCode.SubCommodityBatchNotBelongToSubCommodity;
        }

        this._subCommodityBatchList.push(
            CommodityBatchWithTax.fromCommodityBatch(batch)
        );
        return CommodityCollectionCode.Succeed;
    }

    /**
     * 移除商品批次
     * @param {CommodityBatchWithTax} batch 
     * @returns {boolean}
     */
    removeSubCommodityBatch(batch) {
        const index = this._subCommodityBatchList.indexOf(batch);

        if (index === 0) {
            batch.setCount(null);
            return true;
        } else if (index > 0) {
            this._subCommodityBatchList.splice(index, 1);
            return true;
        }
        return false;
    }

    /**
     * 克隆当前集合
     * data SubCommodityCollection
     * @returns {SubCommodityCollection}
     */
    static clone(data) {
        const cloned = new SubCommodityCollection({
            subCommodity: data.subCommodity
        });

        data._subCommodityBatchList.forEach(element => {
            cloned._subCommodityBatchList.push(CommodityBatchWithTax.clone(element));
        });

        return cloned;
    }

    /**
     * 获取商品总数量
     * @returns {CsDouble}
     */
    getCommodityCount() {
        let value = CsDouble.zero();
        this._subCommodityBatchList.forEach(item => {
            value = value.add(item.count);
        });
        return value;
    }

    /**
     * 获取可空的商品总数量（用于盘点）
     * @returns {CsDouble|null}
     */
    getCommodityCountNullable() {
        let value = null;
        this._subCommodityBatchList.forEach(item => {
            if (item.countOriginal != null) {
                value = value === null
                    ? item.countOriginal
                    : value.add(item.countOriginal);
            }
        });
        return value;
    }

    /**
     * 获取商品总价
     * @returns {CsFundDouble}
     */
    getCommodityPrice() {
        let value = CsFundDouble.zero();
        this._subCommodityBatchList.forEach(item => {
            value = value.add(item.batchPriceWithTax);
        });
        return value;
    }

    /**
     * 获取商品批次列表（可过滤0数量）
     * @param {Object} options
     * @param {boolean} [options.zeroInclude=false] 是否包含0数量
     * @returns {Array<CommodityBatchWithTax>}
     */
    getSubCommodityBatches({ zeroInclude = false } = {}) {
        return this._subCommodityBatchList.filter(item => {
            if (zeroInclude) {
                return item.countOriginal != null;
            } else {
                return item.count.value !== 0;
            }
        });
    }

    /**
   /// 添加规格商品集
  /// 如果与当前已有批次价格一样，当前已有批次数量增加
  /// 如果价格不一样，则创建新的批次
     * @param {Object} params
     * @param {CommodityBatchWithTax|null} params.orgBatch 原有批次
     * @param {CommodityBatchWithTax} params.batch 新批次
     */
    addOrCreateSubCommodityBatch({ orgBatch, batch }) {
        if (orgBatch != null) {
            if (batch.commodity.id === this.subCommodity.id &&
                orgBatch.commodity.id === this.subCommodity.id) {
                orgBatch.copy(batch);
            }
        } else {
            if (batch.commodity.id !== this.subCommodity.id) {
                return;
            }
            this.addSubCommodityBatchWithTax(batch);
        }
    }
}